import { defineStore } from 'pinia';
import { getWeChatList } from '@/api/weixin';
import { WeixinState } from './types';

const useWeixinStore = defineStore('weixin', {
  state: (): WeixinState => ({
    wxList: [],
    loading: false,
    selectedWxid: '', // 当前选中的 mywxid
    selectedAvatar: '', // 当前选中的头像
  }),

  getters: {
    getWxList: (state) => state.wxList,
  },

  actions: {
    // 设置当前选中的 mywxid 和 avatar
    setSelectedWeixin(wxid: string, avatarUrl: string) {
      this.selectedWxid = wxid;
      this.selectedAvatar = avatarUrl;
    },
    // 获取微信列表
    async fetchWxList() {
      if (this.wxList.length > 0) {
        return this.wxList; // 如果已有数据，直接返回
      }

      this.loading = true;
      try {
        const res = await getWeChatList();
        this.wxList = res.data;
        return this.wxList;
      } catch (error) {
        console.error('获取微信列表失败:', error);
        return [];
      } finally {
        this.loading = false;
      }
    },
  },
});

export default useWeixinStore;
